<?php
namespace Nanastroj;

use \Nette\Utils\Strings;


class UserManager {
  
  private $conn;
  
  public function __construct(\Nette\Database\Connection $connection){
     $this->conn = $connection;
  }
  
  public function isLoginFree($login){
    if($this->conn->table('user')->where('login', $login)){
      return false;
    }
    
    return true;
  }
  
  public function isEmailFree($email){
    if($this->conn->table('user')->where('email', $email)){
      return false;
    }
    
    return true;
  }
 
  public function registerNewUser($login, $password, $email){
    $hashSalt = hash('sha512', Strings::random(10));
    $hashPassword = self::getHashPassword($password, $hashSalt);
    
    $stateId = $this->conn->table('user_state')->where('name', 'no_active')->fetch()['id'];
    $roleId = $this->conn->table('role')->where('name', 'user')->fetch()['id'];
    
    $regDate = date("Y.m.d H:i:s", time());
    $activationCode = Strings::random(10);
    
    $this->conn->table('user')->insert(array(
        'role_id' => $roleId,
        'user_state_id' => $stateId,
        'login' => $login,
        'password' => $hashPassword,
        'salt' => $hashSalt,
        'activation_code' => $activationCode,
        'registration_date' => $regDate,
        'email' => $email
    ));
    
    // TODO Send mail 
  }
  
  public function getUserIdByLogin($login){
    $user = $this->conn->table('user')->where('login', $login)->fetch();
    if($user){
      return $user->id;
    }
    
    return false;
  }
  
  public function getUserIdByEmail($email){
    $user = $this->conn->table('user')->where('email', $email)->fetch();
    if($user){
      return $user->id;
    }
    
    return false;
  }
  
  // Jenom pro zmenu z no_active na active - pro jine pripady pouzivat primo changeUserState
  public function activateUser($login, $activationCode){
    $user = $this->conn->table('user')->where('login', $login)->fetch();
    
    if($user && $user->activation_code == $activationCode){
      if($user->user_state->name == 'no_active'){
        $this->changeUserState($user->id, 'active');
      }
    }else{
      return false;
    }
    
    return true;
  }
  
  public function changeUserState($userId, $newState){
    $stateId = $this->conn->table('user_state')->where('name', $newState)->fetch()->id;
    $user = $this->conn->table('user')->where('id', $userId)->fetch();
    if($user){
      $this->conn->table('user')->where('id', $userId)->update(array(
          'user_state_id' => $stateId
      ));
    }
  }
  
  public function changePassword($userId, $newPassword){
    
  }
  
  public static function getHashPassword($password, $salt){
		return hash('sha512', $password . $salt);
	}
}
